package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 问题库Controller
 *
 * @author ruoyi
 * @date 2024-06-11
 */
@Controller
@RequestMapping("/system/knowkedg")
public class QKnowkedgController extends BaseController {

    @Autowired
    private IQRelativeService qRelativeService;

    @Autowired
    private IQMenu1Service qMenu1Service;

    @Autowired
    private IQMenu2Service qMenu2Service;

    @Autowired
    private IQMenu3Service qMenu3Service;

    private String prefix = "system/knowkedg";

    @Autowired
    private IQKnowkedgService qKnowkedgService;

    @RequiresPermissions("system:knowkedg:view")
    @GetMapping()
    public String knowkedg() {
        return prefix + "/knowkedg";
    }



    @GetMapping("/selectRelative/{knowledgId}")
    public String selectRelative(@PathVariable long knowledgId,  ModelMap mmap)
    {

        QKnowkedg qKnowkedg = qKnowkedgService.selectQKnowkedgByKnowledgId(knowledgId);
        mmap.put("qKnowkedg", qKnowkedg);
        return prefix + "/selectRelative";
    }

    /**
     * 查询问题库列表
     */
    @CrossOrigin
    // @RequiresPermissions("system:knowkedg:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(QKnowkedg qKnowkedg) {
        startPage();

        //返回答案
        List<QKnowkedg> list = qKnowkedgService.selectQKnowkedgList(qKnowkedg);
        return getDataTable(list);

    }

    /**
     * 查询相关问题列表
     */
    @CrossOrigin
    // @RequiresPermissions("system:knowkedg:list")
    @PostMapping("/listxgwt/{knowledgId}")
    @ResponseBody
    public TableDataInfo listxgwt(@PathVariable long knowledgId, QKnowkedg qKnowkedg) {
        List<QKnowkedg> listAnswer = new ArrayList<QKnowkedg>();
        startPage();
        long r_id = knowledgId;
        QRelative qRelative = new QRelative();
        qRelative.setKnowledgId(r_id);
        List<QRelative> list2 = qRelativeService.selectQRelativeList(qRelative);
        if (list2.size() > 0) {
            List<String> ids = new ArrayList<String>();
            for (QRelative qr : list2) {
                ids.add(qr.getRelativeId().toString());
            }
            List<QKnowkedg> list3 = qKnowkedgService.selectQKnowkedgList1(ids);
            for (QKnowkedg qk : list3) {
                listAnswer.add(qk);
            }
        }
        return getDataTable(listAnswer);

    }

    public static boolean isNumeric(String str) {
        return str.matches("\\d+");
    }

    /**
     * 人工回答问题列表
     */
    @CrossOrigin
    // @RequiresPermissions("system:knowkedg:list")
    @PostMapping("/question")
    @ResponseBody
    public TableDataInfo question(QKnowkedg qKnowkedg) {
        startPage();
        QMenu1 qMenu1 = new QMenu1();

        if ( isNumeric(qKnowkedg.getQuestion().trim()) )  {

            List<QKnowkedg> list = qKnowkedgService.selectQKnowkedgList(qKnowkedg);
            List<QKnowkedg> listAnswer = new ArrayList<QKnowkedg>();

            QKnowkedg noanswer = new QKnowkedg();
            noanswer.setQuestion(qKnowkedg.getQuestion());
            noanswer.setAnswer1("中心知识库持续更新优化，您的问题暂时没有匹配答案，请工作时间内拨打0731-89938899进行人工咨询，谢谢您的支持");
            noanswer.setAnswer2("中心知识库持续更新优化，您的问题暂时没有匹配答案，请工作时间内拨打0731-89938899进行人工咨询，谢谢您的支持");
            listAnswer.add(noanswer);
            return getDataTable(listAnswer, 2);


        }

//        if (qKnowkedg.getQuestion().contains("CA") || qKnowkedg.getQuestion().contains("ca")) {
//            // 查询知识库返回答案
//            List<QKnowkedg> list = qKnowkedgService.selectQKnowkedgList(qKnowkedg);
//            List<QKnowkedg> listAnswer = new ArrayList<QKnowkedg>();
//            listAnswer.add(list.size() > 0 ? list.get(0) : null);
//
//            return getDataTable(listAnswer, 2);
//        }

        qMenu1.setqContent(qKnowkedg.getQuestion());
        List<QMenu1> listMenu1 = qMenu1Service.selectQMenu1List(qMenu1);

        if (listMenu1.size() > 0) {
            //返回二级目录索引
            QMenu2 qMenu2 = new QMenu2();
            qMenu2.setQ2ParentId(listMenu1.get(0).getqId());
            List<QMenu2> listMenu2 = qMenu2Service.selectQMenu2List(qMenu2);

            return getDataTable(listMenu2, 1);


        } else {

            //查询二级目录，
            QMenu2 qMenu21 = new QMenu2();
            qMenu21.setQ2SubContent(qKnowkedg.getQuestion());
            List<QMenu2> listMenu21 = qMenu2Service.selectQMenu2List(qMenu21);

            if (listMenu21.size() > 0) {

                //返回三级目录索引
                QMenu3 qMenu3 = new QMenu3();
                qMenu3.setQ3ParentId(listMenu21.get(0).getQ2Id());
                List<QMenu3> listMenu3 = qMenu3Service.selectQMenu3List(qMenu3);

                if (listMenu3.size() > 0) {
                    return getDataTable(listMenu3, 1);

                } else {
                    // 查询知识库返回答案
                    List<QKnowkedg> list = qKnowkedgService.selectQKnowkedgList(qKnowkedg);
                    List<QKnowkedg> listAnswer = new ArrayList<QKnowkedg>();
                    if (list.size() > 0) {
//                        listAnswer.add(list.get(0));
//                        //加入相关问题
//                        //加入相关问题
//                        long r_id = Math.toIntExact(list.get(0).getKnowledgId());
//
//
//                        QRelative qRelative = new QRelative();
//
//                        qRelative.setKnowledgId(r_id);
//
//                        List<QRelative> list2 = qRelativeService.selectQRelativeList(qRelative);
//
//                        if (list2.size() > 0) {
//                            List<String> ids = new ArrayList<String>();
//
//                            for (QRelative qr : list2) {
//                                ids.add(qr.getRelativeId().toString());
//                            }
//
//                            List<QKnowkedg> list3 = qKnowkedgService.selectQKnowkedgList1(ids);
//
//                            for (QKnowkedg qk : list3) {
//                                listAnswer.add(qk);
//                            }
//
//                        }

                        if (list.size() == 1) {
                            for(QKnowkedg a: list ){
                                listAnswer.add(a);
                            }
                            return getDataTable(listAnswer, 2);

                        }else{
                            for(QKnowkedg a: list ){
                                listAnswer.add(a);
                            }
                            return getDataTable(listAnswer, 3);

                        }

                    } else {
                        QKnowkedg noanswer = new QKnowkedg();
                        noanswer.setQuestion(qKnowkedg.getQuestion());
                        noanswer.setAnswer1("中心知识库持续更新优化，您的问题暂时没有匹配答案，请工作时间内拨打0731-89938899进行人工咨询，谢谢您的支持");
                        noanswer.setAnswer2("中心知识库持续更新优化，您的问题暂时没有匹配答案，请工作时间内拨打0731-89938899进行人工咨询，谢谢您的支持");
                        listAnswer.add(noanswer);
                        return getDataTable(listAnswer, 2);

                    }

                }


            } else {

                // 查询知识库返回答案
                List<QKnowkedg> list = qKnowkedgService.selectQKnowkedgList(qKnowkedg);
                List<QKnowkedg> listAnswer = new ArrayList<QKnowkedg>();
                if (list.size() > 0) {
//                    listAnswer.add(list.get(0));
//                    //加入相关问题
//                    long r_id = Math.toIntExact(list.get(0).getKnowledgId());
//
//
//                    QRelative qRelative = new QRelative();
//
//                    qRelative.setKnowledgId(r_id);
//
//                    List<QRelative> list2 = qRelativeService.selectQRelativeList(qRelative);
//
//                    if (list2.size() > 0) {
//                        List<String> ids = new ArrayList<String>();
//
//                        for (QRelative qr : list2) {
//                            ids.add(qr.getRelativeId().toString());
//                        }
//
//                        List<QKnowkedg> list3 = qKnowkedgService.selectQKnowkedgList1(ids);
//
//                        for (QKnowkedg qk : list3) {
//                            listAnswer.add(qk);
//                        }
//
//                    }
                    if (list.size() == 1) {
                        for(QKnowkedg a: list ){
                            listAnswer.add(a);
                        }
                        return getDataTable(listAnswer, 2);

                    }else{
                        for(QKnowkedg a: list ){
                            listAnswer.add(a);
                        }
                        return getDataTable(listAnswer, 3);

                    }



                } else {
                    QKnowkedg noanswer = new QKnowkedg();
                    noanswer.setQuestion(qKnowkedg.getQuestion());
                    noanswer.setAnswer1("中心知识库持续更新优化，您的问题暂时没有匹配答案，请工作时间内拨打0731-89938899进行人工咨询，谢谢您的支持");
                    noanswer.setAnswer2("中心知识库持续更新优化，您的问题暂时没有匹配答案，请工作时间内拨打0731-89938899进行人工咨询，谢谢您的支持");
                    listAnswer.add(noanswer);
                    return getDataTable(listAnswer, 2);

                }

            }

        }

    }

    /**
     * 导出问题库列表
     */
    @CrossOrigin
    @RequiresPermissions("system:knowkedg:export")
    @Log(title = "问题库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(QKnowkedg qKnowkedg) {
        List<QKnowkedg> list = qKnowkedgService.selectQKnowkedgList(qKnowkedg);
        ExcelUtil<QKnowkedg> util = new ExcelUtil<QKnowkedg>(QKnowkedg.class);
        return util.exportExcel(list, "问题库数据");
    }

    /**
     * 新增问题库
     */
    @CrossOrigin
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存问题库
     */
    @RequiresPermissions("system:knowkedg:add")
    @Log(title = "问题库", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(QKnowkedg qKnowkedg) {
        return toAjax(qKnowkedgService.insertQKnowkedg(qKnowkedg));
    }


    /**
     * 新增保存关联问题库
     */
    @RequiresPermissions("system:knowkedg:add")
    @Log(title = "问题库", businessType = BusinessType.INSERT)
    @PostMapping("/saveFxqueston")
    @ResponseBody
    public AjaxResult saveFxqueston(QRelative qRelative) {
        return toAjax(qRelativeService.insertQRelative(qRelative));
    }

    /**
     * 删除关联问题库
     */
    @RequiresPermissions("system:knowkedg:add")
    @Log(title = "问题库", businessType = BusinessType.DELETE)
    @PostMapping("/deleteFxqueston")
    @ResponseBody
    public AjaxResult deleteFxqueston(QRelative qRelative) {
        return toAjax(qRelativeService.deleteQRelativeByRId1(qRelative));
    }


    /**
     * 修改问题库
     */
    @CrossOrigin
    @RequiresPermissions("system:knowkedg:edit")
    @GetMapping("/edit/{knowledgId}")
    public String edit(@PathVariable("knowledgId") Long knowledgId, ModelMap mmap) {
        QKnowkedg qKnowkedg = qKnowkedgService.selectQKnowkedgByKnowledgId(knowledgId);
        mmap.put("qKnowkedg", qKnowkedg);
        return prefix + "/edit";
    }

    /**
     * 修改保存问题库
     */
    @CrossOrigin
    @RequiresPermissions("system:knowkedg:edit")
    @Log(title = "问题库", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(QKnowkedg qKnowkedg) {
        return toAjax(qKnowkedgService.updateQKnowkedg(qKnowkedg));
    }

    /**
     * 删除问题库
     */
    @CrossOrigin
    @RequiresPermissions("system:knowkedg:remove")
    @Log(title = "问题库", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(qKnowkedgService.deleteQKnowkedgByKnowledgIds(ids));
    }


    @CrossOrigin
    @ResponseBody
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<QKnowkedg> util = new ExcelUtil<>(QKnowkedg.class);
        List<QKnowkedg> questionList = util.importExcel(file.getInputStream());
        String message = qKnowkedgService.importQuestion(questionList, updateSupport, getLoginName());
        return AjaxResult.success(message);
    }

    @CrossOrigin
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<QKnowkedg> util = new ExcelUtil<QKnowkedg>(QKnowkedg.class);
        return util.importTemplateExcel("知识库问题数据");
    }


}
